// 此文件编写和业务无关的工具方法
export function isJSON(str) {
  if (typeof str == 'string') {
    try {
      var obj = JSON.parse(str);
      if (typeof obj == 'object' && obj) {
        return true;
      } else {
        return false;
      }

    } catch (e) {
      console.log('error：' + str + '!!!' + e);
      return false;
    }
  }
}

export function isUndefined(val) {
  return typeof val === 'undefined';
}

export function isObject(obj) {
  return Object.prototype.toString.call(obj) === '[object Object]';
}

function isPromise(obj) {
  return 'function' == typeof obj.then;
}

// 保证fn返回resolve状态
function toResolvedPromise(fn) {
  return new Promise((resolve, reject) => {
    let result = fn();

    // 非promise结果直接返回
    if (!isPromise(result)) {
      console.log('not promise');
      return resolve(result)
    }

    result.then((data) => {
      resolve(data)
    }).catch((err) => {
      console.log('error:', err);
      resolve(null);
    })
  })
}

// 顺序执行promise
export function runPromiseInSequence(promiseArr) {
  const arr = [];
  async function run() {
    for(let p of promiseArr) {
      const val = await toResolvedPromise(p);
      arr.push(val);
    }
    return arr;
  }
  return run();
}

// 是否是手机号
export function isPhone(phoneNum) {
  const reg = /^1[3-9]\d{9}$/g;
  return reg.test(phoneNum);
}

// 将对象转为key=value字符串，中间&连接
export function convertObj2KV(obj) {
  if (!obj || !Object.keys(obj).length) {
    return '';
  }
  
  const items = [];
  for(let [key, value] of Object.entries(obj)) {
    items.push(`${key}=${value}`);
  }
  return items.join('&');
}

export function base64ToFile(byteString, mimeString, fileName) {
    let ab = new ArrayBuffer(byteString.length);
    let ia = new Uint8Array(ab);
    for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    const blob = new Blob([ab], { type: mimeString });
	
	let file = new File([blob], fileName, {
		type: blob.type,
		lastModified: Date.now()
	});
	return file;
}

// 防抖
export function debounce(func, ms = 1000) {
  let timer;
  return function (...args) {
    const context = this;
    clearTimeout(timer);

    timer = setTimeout(() => {
      func.apply(context, args);
    }, ms);
  }
}

// 节流
export function throttle(func, ms = 1000) {
  let timer;
  return function (...args) {
    if (timer) {
      return;
    }
    const context = this;
    timer = setTimeout(() => {
      func.apply(context, args);
      timer = null;
    }, ms);
  }
}

export function getScreenSize() {
  return new Promise((resolve, reject) => {
    
    //#ifdef APP-PLUS
    const statusHeight = uni.getSystemInfoSync()['statusBarHeight'];
    const contentTop = statusHeight + 44;
    //#endif

    uni.getSystemInfo({
      success: res => {
        // this.$store.commit('setSystemInfo', res);
        let windowHeight, windowWidth;

        // #ifdef APP-PLUS
        windowHeight = res.screenHeight - contentTop - 2;
        windowWidth = res.screenWidth;
        // #endif

        // #ifdef H5
        windowHeight = res.screenHeight - 44;
        windowWidth = res.screenWidth;
        // #endif

        res = {
          windowHeight: windowHeight,
          windowWidth: windowWidth
        }

        return resolve(res)
      }
    })

  })
}
